import {
  Directive,
  ElementRef,
  Renderer2,
} from '@angular/core';

import {
  fromEvent
} from 'rxjs';
import {
  pluck,
} from 'rxjs/operators';

export type EventFn = (e: any) => void;

@Directive({
  selector: '[appHCarouselContent]'
})
export class HCarouselContentDirective {

  private _el: any;
  activeClass = 'active';
  set style(value: any) {
    if (value) {
      Object.keys(value).forEach(prop => {
        this.renderer.setStyle(this._el, prop, value[prop]);
      });
    }
  }
  // 绑定触摸事件
  set moveFn(fn: EventFn) {
    this.handleTouchEvent(this._el, fn, 'touchmove');
  }
  set startFn(fn: EventFn) {
    this.handleTouchEvent(this._el, fn, 'touchstart');
  }
  set endFn(fn: EventFn) {
    this.handleTouchEvent(this._el, fn, 'touchend');
  }
  set isActive(has: boolean) {
    if (has) {
      this.renderer.addClass(this._el, this.activeClass);
    } else {
      this.renderer.removeClass(this._el, this.activeClass);
    }
  }

  // 触摸事件绑定
  handleTouchEvent (el: any, callback: EventFn, type: string) {
    callback = typeof callback === 'function' ? callback : (e) => {};
    const moveEvent = fromEvent( el, type);
    moveEvent.pipe(
      pluck('changedTouches', '0')
    ).subscribe((e: any) => {
      callback(e);
    });
  }

  constructor(private el: ElementRef, private renderer: Renderer2) {
    this._el = el.nativeElement;
  }

}
